﻿#include "CameraFinder.h"
#include <QDir>
#include <QDebug>

namespace Qly
{

CameraFinder::CameraFinder(QString path, QObject *parent)
{
    QDir dir(path);
    QStringList filters;
    filters << "Camera*.dll";
    QStringList dllNames = dir.entryList(filters, QDir::Files, QDir::NoSort);

    foreach (QString name, dllNames) {
        QString fullName = path + "/" + name;
        qDebug() << "CameraFinder: dll = " << fullName;
        CameraLoader * loader = new CameraLoader(fullName, parent);
        if( loader->isValid() )
        {
            m_loaders << loader;
        }
        else
        {
            qDebug() << "CameraFinder: bad dll = " << fullName;
            delete loader;
        }
    }
}

CameraFinder::~CameraFinder()
{

}

IndustryCamera *CameraFinder::defaultCamera(QSet<CameraType> types, QObject *parent)
{
    IndustryCamera * p = nullptr;
    for(int i = 0; i < m_loaders.count(); i++)
    {
        CameraFactoryInterface * cfi = m_loaders[i]->defaultInstance();
        p = cfi->defaultCamera( parent);
        if(p != nullptr )
        {
            return p;
        }
    }
    return p;
}

QStringList CameraFinder::allCameraName(QSet<CameraType> types)
{
    qDebug() << "CameraFinder::allCameraName(QSet<CameraType> types)";
    QStringList list;
    for(int i = 0; i < m_loaders.count(); i++)
    {
        CameraFactoryInterface * cfi = m_loaders[i]->defaultInstance();
        QString vender = cfi->vendorName();
        qDebug() << "Vender Name = " << vender;
        QList<IndustryCameraInfo> pl = cfi->availableCameras(types);
        foreach (IndustryCameraInfo info, pl) {
            list << QString("%1 : %2").arg(vender).arg(info.cameraID);
        }
    }
    return list;
}

IndustryCamera *CameraFinder::findCameraByName(QString rawName, QObject *parent)
{
    IndustryCamera * p = nullptr;
    for(int i = 0; i < m_loaders.count(); i++)
    {
        CameraFactoryInterface * cfi = m_loaders[i]->defaultInstance();
        p = cfi->findCameraByName(rawName, parent);
        if(p != nullptr )
        {
            return p;
        }
    }
    return p;
}

bool CameraFinder::release(IndustryCamera *camera)
{
    for(int i = 0; i < m_loaders.count(); i++)
    {
        CameraFactoryInterface * cfi = m_loaders[i]->defaultInstance();
        bool on = cfi->release(camera);
        if( on )
        {
            camera = nullptr;
            return true;
        }
    }
    return false;
}

}
